package components;

import java.security.InvalidParameterException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.example.remotecontrol.R;

import common.Constant;
import data.SMSCommand;
import data.SendingSMSCommand;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class SMSCommandManager {
	public final static String TEST_PHONE_NUMBER = "5556";


	private static String mPhoneNumber = null;
	public final static String TAG = SMSCommandManager.class.getSimpleName();

	private static final String SHARED_PREFERENCE_KEY_PHONE_NUMBER = "phone_number";

	
	public static void sendMessageWithDialog(final Context context,
			final SMSCommand smsCommand) {
		 if (SharePreferencesManager.getDontShowAgain(context)) {
		 sendSMSMessage(context, smsCommand);
		 } else {
		// custom dialog
		final Dialog dialog = new Dialog(context);
		dialog.setContentView(R.layout.dialog_power_confirm);
		dialog.setTitle(context.getString(R.string.alert_title));

		// set the custom dialog components - text, image and button
//		 TextView text = (TextView) dialog.findViewById(R.id.text);
//		 text.setText("Android custom dialog example!");
//		 ImageView image = (ImageView) dialog.findViewById(R.id.image);
//		 image.setImageResource(R.drawable.ic_launcher);

		Button dialogButton = (Button) dialog.findViewById(R.id.btn_OK);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				 CheckBox chk = (CheckBox)
				 dialog.findViewById(R.id.chk_not_show_again);
				 if (chk.isChecked()) {
				 SharePreferencesManager.dontShowPowerConfirm(context);
				 }

				sendSMSMessage(context, smsCommand);
				dialog.dismiss();
			}
		});

		Button cancelButton = (Button) dialog.findViewById(R.id.btn_cancel);
		cancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
		 }
	}

	public static void sendSMSMessage(Context context, SMSCommand smsCommand) {
		try {
			SMSCommandManager.sendMessage(context, smsCommand);
		} catch (InvalidParameterException ex) {
			// TODO: handle exception
			final AlertDialog alertDialog = AlertDialogManager
					.createAlertDialog(
							context,
							R.string.alert_title,
							R.string.message_exception_when_no_setup_phone_number,
							R.string.OK, new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});

			alertDialog.show();

		} catch (IllegalArgumentException ex) {
			// TODO: handle exception
			final AlertDialog alertDialog = AlertDialogManager
					.createAlertDialog(context, R.string.alert_title,
							R.string.message_send_message_fail, R.string.OK,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});

			alertDialog.show();
		}

	}
	
	/**
	 * 
	 * @param context
	 * @param cmd
	 * @param content
	 * @exception InvalidParameterException
	 *                {@link InvalidParameterException}
	 * @exception IllegalArgumentException
	 *                {@link IllegalArgumentException}
	 */
	private static void sendMessage(Context context, SMSCommand smsCommand) {
		
		if (smsCommand == null) {
			throw new InvalidParameterException();
		}
		
		//Get message
		String message = SMSSendingCommandFactory.createSMSCommandString(smsCommand);

		String phoneNumber = smsCommand.getPhoneNumber();
		if (phoneNumber == null) {
			
			if (phoneNumber == null) {
			throw new InvalidParameterException();
			}
		}

		//Send message
		SmsManager smsManager = SmsManager.getDefault();
		try {
			smsManager.sendTextMessage(phoneNumber, null, message, null, null);
			Log.d(TAG, "Sent to phone number " + phoneNumber + " with message "
					+ message);

			String toastMessage = String.format(context.getString(R.string.message_format_send_message_successfull), phoneNumber);
			Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
		} catch (IllegalArgumentException ex) {
			throw new IllegalArgumentException();
		}

	}

	/**
	 * 
	 * @param context
	 * @return NULL when default. Else return number phone
	 */
	public static String sharedPhoneNumber(Context context) {
		if (mPhoneNumber == null || mPhoneNumber.isEmpty()) {
			mPhoneNumber = loadPhoneNumber(context);
		}
		return mPhoneNumber;
	}

	private static String loadPhoneNumber(Context context) {
		// context.getApplicationInfo();
		// TODO Auto-generated method stub
		// boolean isDebuggable = (0 != (context.getApplicationInfo().flags &=
		// ApplicationInfo.FLAG_DEBUGGABLE));

		String phoneNumber = null;

		// TODO: Load Phone Number
		SharedPreferences spref = context.getSharedPreferences(
				Constant.KEY_SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
		phoneNumber = spref.getString(SHARED_PREFERENCE_KEY_PHONE_NUMBER, null);

		return phoneNumber;
	}

	/**
	 * 
	 * @param newPhoneNumber
	 * @exception InvalidParameterException
	 * @exception NumberFormatException
	 */
	public static void setPhoneNumber(Context context, String newPhoneNumber) {
		if (!validatePhoneNumber(newPhoneNumber)) {
			throw new NumberFormatException("Phone number is invalid");
		}

		if (context == null) {
			throw new InvalidParameterException("Context is null");
		}

		SharedPreferences spref = context.getSharedPreferences(
				Constant.KEY_SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
		Editor edit = spref.edit();
		edit.putString(SHARED_PREFERENCE_KEY_PHONE_NUMBER, newPhoneNumber);
		edit.commit();
		mPhoneNumber = newPhoneNumber;
	}

	public static boolean validatePhoneNumber(String phoneNumber) {
		String phoneNumPattern = "^[0-9.()-]{10,13}$";
		Pattern pattern = Pattern.compile(phoneNumPattern);
		Matcher matcher = pattern.matcher(phoneNumber);

		boolean result = matcher.matches();
		if (result || phoneNumber.endsWith("5554") || phoneNumber.endsWith("5556")) {
			//String match = matcher.group();
			//Log.d(TAG, "PhoneNumber valid" + match);
			return true;
		}

		return result;
	}
}
